package com.hksj.common.config.utils;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

public class RequestContextHolderUtils {

        /**
         * 获取HttpServletRequest请求对象
         *
         * @return {@link HttpServletRequest}
         */
        public static HttpServletRequest getRequest() {
            return getRequestAttributes().getRequest();
        }

        /**
         * 获取HttpServletResponse响应对象
         *
         * @return {@link HttpServletResponse}
         */
        public static HttpServletResponse getResponse() {
            return getRequestAttributes().getResponse();
        }

        /**
         * 获得会话
         *
         * @return {@link HttpSession}
         */
        public static HttpSession getSession() {
            return getRequest().getSession();
        }
        /**
         * 设置会话属性
         *
         * @param name  名字
         * @param value 值
         */
        public static void setSessionAttribute(String name, Object value) {
            getSession().setAttribute(name, value);
        }

        /**
         * 获得会话属性
         *
         * @param name 名字
         * @return {@link Object}
         */
        public static Object getSessionAttribute(String name) {
            return getSession().getAttribute(name);
        }

        /**
         * servlet容器请求属性
         *
         * @return {@link ServletRequestAttributes}
         */
        public static ServletRequestAttributes getRequestAttributes() {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        }

        /**
         * 得到servlet上下文
         *
         * @return {@link ServletContext}
         */
        public static ServletContext getServletContext() {
            return Objects.requireNonNull(ContextLoader.getCurrentWebApplicationContext()).getServletContext();
        }
    }